using System;
using UnityEngine.Playables;

namespace UnityEngine.Recorder.Timeline
{
	public class RecorderPlayableBehaviour : PlayableBehaviour
	{
		private PlayState m_PlayState;

		private WaitForEndOfFrameComponent endOfFrameComp;

		private bool m_FirstOneSkipped;

		public Action OnEnd;

		public RecordingSession session
		{
			get;
			set;
		}

		public override void OnGraphStart(Playable playable)
		{
			if (session != null)
			{
				session.SessionCreated();
				m_PlayState = PlayState.Paused;
			}
		}

		public override void OnGraphStop(Playable playable)
		{
			if (session != null && session.recording)
			{
				session.EndRecording();
				session.Dispose();
				session = null;
				if (OnEnd != null)
				{
					OnEnd();
				}
			}
		}

		public override void PrepareFrame(Playable playable, FrameData info)
		{
			if (session != null && session.recording)
			{
				session.PrepareNewFrame();
			}
		}

		public override void ProcessFrame(Playable playable, FrameData info, object playerData)
		{
			if (session != null && endOfFrameComp == null)
			{
				endOfFrameComp = session.m_RecorderGO.AddComponent<WaitForEndOfFrameComponent>();
				endOfFrameComp.m_playable = this;
			}
		}

		public override void OnBehaviourPlay(Playable playable, FrameData info)
		{
			if (session != null)
			{
				m_PlayState = PlayState.Playing;
				session.BeginRecording();
			}
		}

		public override void OnBehaviourPause(Playable playable, FrameData info)
		{
			if (session == null)
			{
				return;
			}
			if (session.recording && m_PlayState == PlayState.Playing)
			{
				session.EndRecording();
				session.Dispose();
				session = null;
				if (OnEnd != null)
				{
					OnEnd();
				}
			}
			m_PlayState = PlayState.Paused;
		}

		public void FrameEnded()
		{
			if (session != null && session.recording)
			{
				session.RecordFrame();
			}
		}
	}
}
